﻿using Microsoft.EntityFrameworkCore;
using Vote.Project001.Core.Database.Model;
using Vote.Project001.Core.Infrastructure;

namespace Vote.Project001.Core.Framework
{
    public class UserManager : Singleton<UserManager>
    {
        private bool _isInitialize = false;
        private readonly List<Database.Model.User> _users = new List<Database.Model.User>();

        private readonly Dictionary<string, Database.Model.User> _idToUserDictionary =
            new Dictionary<string, Database.Model.User>();

        private readonly object _lock = new object();

        protected override void OnInitialize()
        {
            if (_isInitialize) return;

            lock (_lock)
            {
                if (!_isInitialize)
                {
                    using var dbContext = new Database.DatabaseContext();
                    _users.AddRange(dbContext.Users.AsNoTracking());
                    foreach (var user in _users)
                    {
                        _idToUserDictionary.Add(user.UserId, user);
                    }
                }

                _isInitialize = true;
            }
        }

        public Database.Model.User? this[string userId] => _idToUserDictionary.ContainsKey(userId) ? _idToUserDictionary[userId] : null;

        public User? GetUser(string userId)
        {
            lock (_lock)
            {
                return _idToUserDictionary.ContainsKey(userId) ? _idToUserDictionary[userId] : null;
            }
        }

        public void AddUser(string userId, string userName)
        {
            lock (_lock)
            {
                if (_idToUserDictionary.ContainsKey(userId)) return;

                using var dbContext = new Database.DatabaseContext();
                dbContext.Users.Add(new User() { Name = userName, UserId = userId });
                dbContext.SaveChanges();

                var u = new User() { Name = userName, UserId = userId };
                _users.Add(u);
                _idToUserDictionary.Add(u.UserId, u);
            }
        }

    }
}
